#include "dayleave.h"
#include<QJsonArray>
#include<QJsonObject>
#include<QJsonDocument>
#include<iostream>


DayLeave::DayLeave(const std::string date)
{
    this->date = date;
}



bool DayLeave::addLeave(const OneLeave oneleave)
{
    //TODO check ever exist
    this->leaves.push_back(oneleave);

}

std::string DayLeave::toJson(){
    QJsonObject jsonObj;
    jsonObj.insert("date",QString::fromStdString(this->date));
    QJsonArray jsonArr;
    for(int i=0;i<leaves.size();i++){
        QJsonObject l;
        l.insert("m_id",QString::fromStdString(leaves.at(i).m_id));
        l.insert("m_name",QString::fromStdString(leaves.at(i).m_name));
        l.insert("reason",QString::fromStdString(leaves.at(i).reason));
        l.insert("time",leaves.at(i).time);
        jsonArr.append(l);
    }
    jsonObj.insert("leaves",jsonArr);
    QJsonDocument jd(jsonObj);
    QString s;
    s.prepend(jd.toJson());
    return s.toStdString();
}

bool DayLeave::initFromJsonString(const std::string & json){
    try {
        QJsonDocument jd = QJsonDocument::fromJson(QByteArray::fromStdString(json));
        QJsonObject jo = jd.object();

        QJsonValue jv = jo.value("date");
        if (jv.isString()){
            if(jv.toString().toStdString()==date){
                return false;
            }
        }
        QJsonValue jva = jo.value("leaves");
        if(jva.isArray()){
            QJsonArray ja = jd.array();
            for(int i=0;i<ja.size();i++){
                QJsonObject jo = ja.at(i).toObject();
                leaves.push_back(OneLeave{jo.value("m_id").toString().toStdString(),
                                          jo.value("m_name").toString().toStdString(),
                                          jo.value("m_name").toString().toStdString(),
                                          jo.value("m_name").toInt()});
            }
        }
        return true;
    } catch (QJsonParseError e) {
         return false;
    }
}
